package seatiger.tomcat.catalina.core;

import javax.servlet.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 管理 和执行 Filter
 */
public class ApplicationFilterChain implements FilterChain {

    private List<ApplicationFilterConfig> filter = new ArrayList();

    private Servlet servlet;

    private Iterator<ApplicationFilterConfig> iterator;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
        iterator = iterator == null ? filter.iterator() : iterator;
        if (iterator.hasNext()){
            ApplicationFilterConfig filterConfig = iterator.next();
            try {
                Filter filter = filterConfig.getFilter();
                filter.doFilter(request,response,this);
                return;
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        if (servlet != null){
            servlet.service(request,response);
        }
    }

    public void setServlet(Servlet servlet) {
        this.servlet = servlet;
    }
    public void addFilter(FilterConfig filterConfig){
        filter.add((ApplicationFilterConfig) filterConfig);
    }
}
